<?php
/*
This source file is a part of Rhubarb gallery

http://code.google.com/p/rhubarb-gallery/

Copyright (c) 2010 Christian Leberfinger

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

set_exception_handler('exception_handler');

include_once 'config/config.inc.php';

$secretFile = 'config/secret.php';
include_secret($secretFile);
if(!@include_once $secretFile)
{
	die("cannot include secret file");
}

$crypt = new Encryption($_SECRET);
include_once 'class.Album.php'; 
include_once 'auth.php';

//setlocale(LC_ALL, "de_DE");
 
/*************/
/* FUNCTIONS */
/*************/

function exception_handler($ex) 
{
	echo $ex->getMessage();
}

function trace($definedVars, $debugBacktrace)
{
	print($debugBacktrace['function'].' : '.$debugBacktrace['line']);
	print(print_r($definedVars, true));	
}

function getAlbums() 
{
	$path = 'pictures';
	$files = array();
	foreach(new DirectoryIterator($path) as $file)
	{
		$filename = $file->getFilename();
		
		if($file->isDir() && !$file->isDot() )
		{
			if(substr($filename, 0, 1) == '.')
				continue;
						
			$files[] = $file->getPathname();
		}
	}
	sort($files, SORT_LOCALE_STRING);
	return $files;
}

class Encryption 
{
	/* a lot of this class was inspired by comments from php.net users */
	
	function __construct($secret) 
	{
		$this->secret = $secret;
		$this->algorithm = MCRYPT_BLOWFISH;
		$this->mode = 'cbc';
		$this->iv = '12345678'; //TODO make IV random for each installation
		$this->initEncryption();
	}
	
	function __destruct()
	{
	}
	
	function initEncryption()
	{
		$this->cipher = mcrypt_module_open($this->algorithm, '', $this->mode, '');
		
		$ivSize = mcrypt_enc_get_iv_size($this->getCipher());
		$keySize = mcrypt_enc_get_key_size($this->getCipher());
		$this->key = substr($this->secret, 0, $keySize);
	}
	
	function getCipher()
	{
		return $this->cipher;
	}
	
	function encrypt($data) 
	{
		mcrypt_generic_init($this->cipher, $this->key, $this->iv);
		
		$data = mcrypt_generic($this->cipher, $this->pad($data));
		
		mcrypt_generic_deinit($this->cipher);
		return base64_encode($data);
	}
	
	function decrypt($data)
	{
		$data = base64_decode($data);
		mcrypt_generic_init($this->cipher, $this->key, $this->iv);
		
		$decoded = mdecrypt_generic($this->cipher, $data);
		
		mcrypt_generic_deinit($this->cipher);
		return $this->unpad($decoded);
	}
	
	/* taken from php.net comments */
	function pad($text) 
	{
	  /* Add a single 0x80 byte and let PHP pad with 0x00 bytes. */
	  return pack("a*H2", $text, "80");
	}
	
	/* taken from php.net comments */
	function unpad($text) 
	{
	  /* Return all but the trailing 0x80 from text that had the 0x00 bytes removed */
	  return substr(rtrim($text, "\0"), 0, -1);
	}
}

function out($string)
{
	echo $string.'<br/>';
}

function include_secret($secretFile)
{
	if(!file_exists($secretFile))
	{
		/* create a new secret */
		$randomString = uniqid(rand(), TRUE);
		$secret = crypt_pass($randomString);

		$f = fopen($secretFile, 'w') or die('can not write to '.$secretFile. '. Maybe you have got to set writing permissions on parent directory');

		$s = "<?php \n";
		$s .= '$_SECRET=\''.$secret.'\';';
		$s .= "\n?>";

		/* write secret to secret.php */
		fwrite($f, $s);

		fflush($f);
		fclose($f);
	}
}

function getSecret()
{
	global $_SECRET;
	return $_SECRET;
}

function crypt_pass($pass, $salt=NULL)
{
	$salt_len=7;
	$algo='sha512';

	if (!$salt || strlen($salt) < $salt_len)
	{
		$salt=uniqid(rand(), TRUE);     // get unique string (length==23)
	}
	$salt=substr($salt, 0, $salt_len);

	$hashed=hash($algo, $salt.$pass);

	return $hashed;
}

function rghash($string) 
{
	return hash_hmac('sha256', $string, $_SECRET);
}

function isPicture($filename)
{
	$extension = getFileSuffix($filename);
	return in_array($extension, array('.jpg','.jpeg'));
}

function getFileSuffix($filename)
{
	return strtolower(substr($filename, strrpos($filename, '.')));
}

function fout($string) 
{
	$filename = "log.txt";
	$fh = fopen($filename, 'a');
	fwrite($fh, $string);
	fclose($fh);
}

?>